# -*- coding: utf-8 -*-
import json
from abc import ABC

from tornado.websocket import WebSocketHandler
from tornado.ioloop import PeriodicCallback
from app.views import CommonHandler
from app.tools.utils import dt


class SensorSockHandler(WebSocketHandler, ABC):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 启动回调任务
        self.callback = PeriodicCallback(callback=self.send, callback_time=5000)

    def send(self):
        if self.ws_connection is None or self.ws_connection.is_closing():
            self.close()
            return

        self.write_message(json.dumps({"message": dt()}))

    def open(self):
        self.set_nodelay(True)
        self.callback.start()

    def check_origin(self, origin):
        return True


class SensorHandler(CommonHandler, ABC):
    async def get(self):
        await self.respose(data={"message": dt()})
